package com.nassir.chatroom.thread;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.SocketException;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.nassir.chatroom.constant.Constant;
import com.nassir.chatroom.model.ClientModel;
import com.nassir.chatroom.util.ClientManager;
import com.nassir.chatroom.util.Logs;

public class ServerThread extends Thread {

	private Socket socket = null; 	// 保存与本线程相关的Socket对象
	private int clientNum = 0; 		// 保存本进程的客户计数
//	private boolean isClosed;       // 是否关闭
	
	

	public ServerThread(Socket socket, int num) {
		this.socket  = socket; 
		this.clientNum = num; 
	}

	public void run() {
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(
					socket.getInputStream()));
			String str = null;
			while ((str = br.readLine()) != null) {
				ClientModel clientModel = ClientManager.getInstance().getClient(clientNum);
				String message = "";
				int index = str.indexOf(Constant.SET_CHAT_NAME + Constant.$); 
				if(index != -1){
				    String [] nameArray = StringUtils.split(str, Constant.$);
				    if(nameArray.length < 2) {
				        continue;
				    }
					String loginName = nameArray[1];
					if(StringUtils.isNotEmpty(loginName) || StringUtils.isNotBlank(loginName)){
						clientModel.setClientName("[" + loginName + "]");
						ClientManager.getInstance().remove(clientModel.getClientId());
						ClientManager.getInstance().add(clientModel);
					}
					continue;
				}else{
					message = clientModel.getClientName() + "说：" + str + " \n";
					sendToAllClient(clientModel.getClientId(), message);
				}
				
				
			}
		} catch(SocketException se){
			ClientModel clientModel = ClientManager.getInstance().getClient(clientNum);
			Logs.info(clientModel.getClientName() + "断开连接");
			ClientManager.getInstance().remove(clientModel.getClientId());
		}catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 发送给所有客户端
	 * @author nassir.wen
	 * @date 2012-12-5下午4:30:16
	 * @param senderId
	 * @param message
	 */
	private void sendToAllClient(Integer senderId,String message){
		List<ClientModel> clients = ClientManager.getInstance().getClients(); 
		Logs.info("共发给" + (clients.size()) + "个客户端");
		for(ClientModel m : clients){
			Socket client = m.getClient();
			Logs.info("发送消息到 " + m.getClientName() + client.getInetAddress() + ":"
					+ client.getPort());
			try {
				BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
						client.getOutputStream()));
				bw.write(message);
				bw.flush();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
